<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="省份" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省" clearable>
          <el-option
            v-for="item in provinceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择市" clearable>
          <el-option
            v-for="item in cityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区县" prop="district">
        <el-select v-model="queryParams.district" placeholder="请选择区县" clearable>
          <el-option
            v-for="item in districtOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属单位" prop="affiliatedUnit">
        <el-input
          v-model="queryParams.affiliatedUnit"
          placeholder="请输入所属单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['nongjt:supervisionUnit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['nongjt:supervisionUnit:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['nongjt:supervisionUnit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['nongjt:supervisionUnit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="supervisionUnitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="省份" align="center" prop="province" min-width="100" show-overflow-tooltip />
      <el-table-column label="城市" align="center" prop="city" min-width="100" show-overflow-tooltip />
      <el-table-column label="区县" align="center" prop="district" min-width="120" show-overflow-tooltip />
      <el-table-column label="所属单位" align="center" prop="affiliatedUnit" min-width="200" show-overflow-tooltip />
      <el-table-column label="所属部门" align="center" prop="affiliatedDepartment" min-width="200" show-overflow-tooltip />
      <el-table-column label="单位logo" align="center" prop="unitLogo" min-width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.unitLogo"
            :src="scope.row.unitLogo"
            :preview-src-list="[scope.row.unitLogo]"
            style="width: 40px; height: 40px;"
            fit="cover">
          </el-image>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="配置项" align="center" prop="configurationItems" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.configurationItems" type="info" size="mini">
            {{ getConfigurationItemsText(scope.row.configurationItems) }}
          </el-tag>
          <span v-else>无配置</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['nongjt:supervisionUnit:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['nongjt:supervisionUnit:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监管单位管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="省份" prop="province">
          <el-select v-model="form.province" placeholder="请选择省" @change="handleProvinceChange">
            <el-option
              v-for="item in provinceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="form.city" placeholder="请选择市" @change="handleCityChange">
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区县" prop="district">
          <el-select v-model="form.district" placeholder="请选择区县">
            <el-option
              v-for="item in districtOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属单位" prop="affiliatedUnit">
          <el-input v-model="form.affiliatedUnit" placeholder="请输入所属单位" />
        </el-form-item>
        <el-form-item label="所属部门" prop="affiliatedDepartment">
          <el-input v-model="form.affiliatedDepartment" placeholder="请输入所属部门" />
        </el-form-item>
        <el-form-item label="单位logo">
          <image-upload v-model="form.unitLogo"/>
        </el-form-item>
        <el-form-item label="配置项">
          <el-select v-model="form.configurationItems" placeholder="请选择配置项" multiple>
            <el-option label="标题" value="title" />
            <el-option label="LOGO" value="logo" />
            <el-option label="打印" value="print" />
            <el-option label="首页" value="homepage" />
            <el-option label="四川省追溯平台" value="traceability" />
            <el-option label="大屏权限" value="screen" />
            <el-option label="合格证抬头" value="certificate" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSupervisionUnit, getSupervisionUnit, delSupervisionUnit, addSupervisionUnit, updateSupervisionUnit, checkRegionExists } from "@/api/monitor/njt/supervision/unit";

export default {
  name: "SupervisionUnit",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监管单位管理表格数据
      supervisionUnitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        province: null,
        city: null,
        district: null,
        affiliatedUnit: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        province: [
          { required: true, message: "省份不能为空", trigger: "change" }
        ],
        city: [
          { required: true, message: "城市不能为空", trigger: "change" }
        ],
        district: [
          { required: true, message: "区县不能为空", trigger: "change" }
        ],
        affiliatedUnit: [
          { required: true, message: "所属单位不能为空", trigger: "blur" }
        ],
        affiliatedDepartment: [
          { required: true, message: "所属部门不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 省市区选项
      provinceOptions: [
        { label: '四川省', value: '四川省' },
        { label: '北京市', value: '北京市' },
        { label: '上海市', value: '上海市' },
        { label: '广东省', value: '广东省' }
      ],
      cityOptions: [],
      districtOptions: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询监管单位管理列表 */
    getList() {
      this.loading = true;
      listSupervisionUnit(this.queryParams).then(response => {
        this.supervisionUnitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        province: null,
        city: null,
        district: null,
        affiliatedUnit: null,
        affiliatedDepartment: null,
        unitLogo: null,
        configurationItems: [],
        status: "0",
        remark: null
      };
      this.cityOptions = [];
      this.districtOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监管单位管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSupervisionUnit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改监管单位管理";
        // 加载对应的城市和区县选项
        this.handleProvinceChange(this.form.province);
        this.handleCityChange(this.form.city);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查省市区是否已存在
          if (!this.form.id) {
            checkRegionExists(this.form.province, this.form.city, this.form.district).then(response => {
              if (response.data) {
                this.$modal.msgError("该省市区已存在监管单位，请勿重复添加");
                return;
              }
              this.submitData();
            });
          } else {
            this.submitData();
          }
        }
      });
    },
    submitData() {
      if (this.form.id != null) {
        updateSupervisionUnit(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addSupervisionUnit(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除监管单位管理编号为"' + ids + '"的数据项？').then(function() {
        return delSupervisionUnit(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('nongjt/supervisionUnit/export', {
        ...this.queryParams
      }, `supervisionUnit_${new Date().getTime()}.xlsx`)
    },
    /** 省份变化处理 */
    handleProvinceChange(province) {
      this.form.city = null;
      this.form.district = null;
      this.cityOptions = [];
      this.districtOptions = [];
      
      if (province === '四川省') {
        this.cityOptions = [
          { label: '成都市', value: '成都市' },
          { label: '雅安市', value: '雅安市' },
          { label: '绵阳市', value: '绵阳市' }
        ];
      } else if (province === '北京市') {
        this.cityOptions = [
          { label: '北京市', value: '北京市' }
        ];
      }
    },
    /** 城市变化处理 */
    handleCityChange(city) {
      this.form.district = null;
      this.districtOptions = [];
      
      if (city === '成都市') {
        this.districtOptions = [
          { label: '成华区', value: '成华区' },
          { label: '青白江区', value: '青白江区' },
          { label: '青羊区', value: '青羊区' },
          { label: '天府新区', value: '天府新区' },
          { label: '成都市本级', value: '成都市本级' },
          { label: '新津县', value: '新津县' },
          { label: '彭州市', value: '彭州市' },
          { label: '郫都区', value: '郫都区' }
        ];
      } else if (city === '雅安市') {
        this.districtOptions = [
          { label: '荥经县', value: '荥经县' }
        ];
      } else if (city === '绵阳市') {
        this.districtOptions = [
          { label: '盐亭县', value: '盐亭县' }
        ];
      }
    },
    /** 获取配置项文本 */
    getConfigurationItemsText(configurationItems) {
      if (!configurationItems) return '';
      const configMap = {
        'title': '标题',
        'logo': 'LOGO',
        'print': '打印',
        'homepage': '首页',
        'traceability': '四川省追溯平台',
        'screen': '大屏权限',
        'certificate': '合格证抬头'
      };
      return configurationItems.split(',').map(item => configMap[item] || item).join(', ');
    }
  }
};
</script>
